//
//  ProxyViewController.m
//  ICrEAM
//
//  Created by mac on 16/10/24.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ProxyViewController.h"
#import "ICMProxySearchModel.h"
#import "ICMProxySearchViewCell.h"
#import "ICMTitleTextFeildView.h"
#import "ICMDatePickerView.h"
#import "NSDate+convenience.h"
#import "ICMProxyPreviewViewController.h"
#import "ICMProxyHomePageViewController.h"
#import "ICMProxyBasicInfoModel.h"
#import "ICMRepairMaintenanceModel.h"
#import "ICMRepairPartsModel.h"
#import "ICMProxyActivityModel.h"
#import "ICrEAMUser.h"
#import "PACACalendarView.h"
#import "ICMStationModel.h"
#define CellHeight ActualHeight(95)

@interface ProxyViewController ()<UITableViewDelegate,UITableViewDataSource,ICMDatePickerViewDelegate,ICMProxySearchCellDelegate,UITextFieldDelegate,PACACalendarViewDelegate>
@property (nonatomic, strong) UITableView *proxySearchList;//tableview
@property (nonatomic, strong) ICMTitleTextFeildView *labelFrom;//开始时间label
@property (nonatomic, strong) ICMTitleTextFeildView *labelTo;//结束时间label
@property (nonatomic, strong) PACACalendarView *pickerFrom;//开始时间选择器
@property (nonatomic, strong) PACACalendarView *pickerTo;//结束时间选择器
@property (nonatomic, strong) UITextField * searchText;//搜索框
@property (nonatomic, strong) NSMutableArray *activityModels;//活动model
@property (nonatomic, strong) NSMutableArray *activityTempModels;//add del用
@property (nonatomic, strong) NSDate *selectedDateFrom;//开始时间
@property (nonatomic, strong) NSDate *selectedDateTo;//结束时间
@property (nonatomic, assign) BOOL hasNext;//是否存在下一页
@property (nonatomic, assign) int pageNo;//页数
@property (nonatomic, assign) BOOL isSearchByDate;//是否根据时间查询

//根据活动里面项目和零件  和   项目和零件  生成对应关系数据字典
@property (nonatomic, strong) NSMutableDictionary *labourAndPartsExistDic;
@end

@implementation ProxyViewController

-(NSMutableArray *)activityTempModels{
    if (!_activityTempModels) {
        _activityTempModels = [NSMutableArray array];
    }
    return _activityTempModels;
}

-(NSMutableArray *)activityModels{
    if (!_activityModels) {
        _activityModels = [NSMutableArray array];
    }
    return _activityModels;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isSearchByDate = NO;
    self.pageNo = 1;
    [self getTodayWithString:@"" start:@"" end:@""];
    self.navigationItem.title=@"委托书查询";
    self.edgesForExtendedLayout=UIRectEdgeNone;
    // Do any additional setup after loading the view from its nib.
    UIView *topBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ActualHeight(40))];
    topBar.backgroundColor = Color(0xE5EBEB);
    
    self.view.backgroundColor = BackgroundColor_White;
    
    //委托书查询
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(ActualWidth(80), 0, ActualWidth(100), ActualHeight(40))];
    
    title.text = @"委托书查询";
    title.textColor = TitleColor;
    title.textAlignment = NSTextAlignmentCenter;
    title.font = NaviFont;
    
    [topBar addSubview:title];
    
    UIView *underLine = [[UIView alloc]initWithFrame:CGRectMake(ActualWidth(80), ActualHeight(39), ActualWidth(100), 1)];
    
    underLine.backgroundColor = TitleColor;
    
    [topBar addSubview:underLine];
    
    [self.view addSubview:topBar];
    
    //搜索框
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth-ActualWidth(400), ActualHeight(4), ActualWidth(360), ActualHeight(32))];
    
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.cornerRadius = ActualHeight(32)/2.0;
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ActualWidth(4), ActualHeight(2), ActualWidth(28), ActualHeight(28))];
    
    searchImage.image = [UIImage imageNamed:GetCar_SearchIcon];
    
    [searchView addSubview:searchImage];
    
    UITextField * searchText = [[UITextField alloc]initWithFrame:CGRectMake(ActualWidth(32), 0, ActualWidth(360)-ActualWidth(32), ActualHeight(32))];
    searchText.delegate = self;
    searchText.returnKeyType = UIReturnKeySearch;
    searchText.placeholder = @"车牌号,送修人姓名,送修人手机，服务顾问";
    searchText.font = [UIFont systemFontOfSize:14];
    [searchView addSubview:searchText];
    [self.view addSubview:searchView];
    self.searchText = searchText;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.searchText];
    
    //headerview
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, ActualHeight(40), ScreenWidth, CellHeight)];
    
    self.labelFrom = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(ActualWidth(75), ActualHeight(10), ActualWidth(150), ActualHeight(75)) title:@"开单时间" addTarget:self selector:@selector(clickCalenderBtnFrom)];
    
    UIButton *btnFrom = [[UIButton alloc]initWithFrame:CGRectMake(self.labelFrom.rightEdge+2, ActualHeight(40), ActualWidth(30), ActualWidth(30))];
    [btnFrom addTarget:self action:@selector(clickCalenderBtnFrom) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ActualHeight(30), ActualWidth(30))];
    imageView.image = [UIImage imageNamed:Appointment_Calendar];
    [btnFrom addSubview:imageView];
    
    UILabel *labelText = [[UILabel alloc]initWithFrame:CGRectMake(btnFrom.rightEdge+10, btnFrom.y, ActualWidth(30), ActualHeight(30))];
    
    labelText.text = @"至";
    labelText.textColor = Color(0x666666);
    
    self.labelTo = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(labelText.rightEdge+10, ActualHeight(10), ActualWidth(150), ActualHeight(75)) title:@" " addTarget:self selector:@selector(clickCalenderBtnTo)];
    
    UIButton *btnTo = [[UIButton alloc]initWithFrame:CGRectMake(self.labelTo.rightEdge+2, ActualWidth(40), ActualWidth(30), ActualWidth(30))];
    [btnTo addTarget:self action:@selector(clickCalenderBtnTo) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *imageViewTo = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ActualHeight(30), ActualWidth(30))];
    imageViewTo.image = [UIImage imageNamed:Appointment_Calendar];
    
    self.labelTo.backgroundColor = Color(0xF4F5F7);
    
    [btnTo addSubview:imageViewTo];
    
    UIButton *btnSearch = [[UIButton alloc]initWithFrame:CGRectMake(btnTo.rightEdge+ActualWidth(30), ActualHeight(20), ActualWidth(50), ActualHeight(60))];
    
    [btnSearch addTarget:self action:@selector(searchByDate) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *imageViewSearch = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ActualWidth(30), ActualHeight(30))];
    imageViewSearch.image = [UIImage imageNamed:Appointment_SearchBtn];
    
    UILabel *labelSearch = [[UILabel alloc]initWithFrame:CGRectMake(0, imageViewSearch.bottomEdge, ActualWidth(50), ActualHeight(20))];
    labelSearch.text = @"查找";
    labelSearch.textColor = TitleColor;
    [btnSearch addSubview:imageViewSearch];
    [btnSearch addSubview:labelSearch];
    
    headerView.backgroundColor = Color(0xF1F3F3);
    [headerView addSubview:self.labelFrom];
    [headerView addSubview:btnFrom];
    [headerView addSubview:labelText];
    [headerView addSubview:self.labelTo];
    [headerView addSubview:btnTo];
    [headerView addSubview:btnSearch];
    
    [self.view addSubview:headerView];
    self.labelFrom.contentText = [ICrEAMTool getNowDate];
    self.labelTo.contentText = [ICrEAMTool getNowDate];
    //tableview
    [self.view addSubview:self.proxySearchList];
    
    self.hasNext = YES;
    [self setRefresh];
    
    
    //保存委托书后通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSavedProxy:) name:@"DidSavedProxy" object:nil];
}

#pragma mark 搜索框默认大写
//默认支持大写
- (void)textFiledEditChanged:(NSNotification *)obj {
    UITextField *textField = obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            textField.text= toBeString.uppercaseString;
        }else{
            // 有高亮选择的字符串
        }
    }else {
        textField.text = textField.text.uppercaseString;
    }
}

#pragma mark 详情页保存后返回列表页重新刷新列表页数据
- (void)didSavedProxy:(NSNotification *)notification
{
    //重新刷新数据
    self.pageNo = 1;
    if (self.isSearchByDate) {
        [self getTodayWithString:@"" start:self.labelFrom.contentText end:self.labelTo.contentText];
    } else {
        [self getTodayWithString:self.searchText.text start:@"" end:@""];
    }
}

#pragma mark 设置上拉加载
//上拉加载
- (void)setRefresh {
    __weak ProxyViewController *my = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.hasNext) {
            self.pageNo++;
            if (self.isSearchByDate) {
                [my getTodayWithString:@"" start:self.labelFrom.contentText end:self.labelTo.contentText];
            } else {
                [my getTodayWithString:self.searchText.text start:@"" end:@""];
            }
        } else {
            [self.proxySearchList.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据了" forState:MJRefreshStateNoMoreData];
    self.proxySearchList.mj_footer = footer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
    
}

- (UITableView *)proxySearchList{
    if(!_proxySearchList){
        _proxySearchList = [[UITableView alloc]initWithFrame:CGRectMake(0, ActualHeight(40)+CellHeight+1, ScreenWidth, ScreenHeight-NavBarAndStatusHeight-(ActualHeight(40)+CellHeight))];
        _proxySearchList.delegate = self;
        _proxySearchList.dataSource = self;
        _proxySearchList.backgroundColor = BackgroundColor_White;
        [_proxySearchList registerClass:[ICMProxySearchViewCell class] forCellReuseIdentifier:@"ICMProxySearchViewCell"];
        _proxySearchList.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        _proxySearchList.tableFooterView.backgroundColor = [UIColor whiteColor];
        _proxySearchList.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _proxySearchList;
}

#pragma mark 选择列表数据
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ICMProxySearchModel *model = self.dataSource[indexPath.row];
    //    model.proxyID
    ICrEAMUser *user = [ICrEAMUser shareICrEAMUser];
    NSString *isMaster = [ICrEAMTool getCodeModelForCode:user.IS_SERVICE_ADVISOR_MASTER].desc;
    //app生成的可以修改，是总监或者服务顾问是自己才可以编辑
//    if([model.IS_APP isEqualToString:@"12781001"] && ([model.proxyType isEqualToString:@"21021001"] || [model.proxyType isEqualToString:@"21021004"]) &&
//       ([isMaster isEqualToString:@"是"]|| [user.employee_NO isEqualToString:model.assistantCode]))
//        
//    {
//        [self didClickCellWithRO_NO:model.proxyID type:@"0"];
//        
//    }else{
//        [self showText:@"PC端创建的委托书，请在PC上进行编辑！"];
//    }
    if([model.IS_APP isEqualToString:ICMEnumIntToString(ICMEnumYESOrNOYES)])
    {
        if([model.proxyType isEqualToString:ICMEnumIntToString(ICMEnumProxyTypeNew)] || [model.proxyType isEqualToString:ICMEnumIntToString(ICMEnumProxyTypeFromAPP)])
        {
            if([isMaster isEqualToString:@"是"] || [user.employee_NO isEqualToString:model.assistantCode])
            {
                [self didClickCellWithRO_NO:model.proxyID type:@"0" andProxyStatus:model.proxyType];
            }else{
                 [self showText:@"您不能操作其他服务顾问的委托书！"];
            }
        }
        else
        {
            if([model.proxyType isEqualToString:ICMEnumIntToString(ICMEnumProxyTypeHasSubmit)])
            {
                [self showText:@"该委托书已提交结算！"];
            }
            if([model.proxyType isEqualToString:ICMEnumIntToString(ICMEnumProxyTypeHasBalance)])
            {
                [self showText:@"该委托书已结算！"];
            }
        }
    }else
    {
        [self showText:@"PC端创建或编辑过的委托书，请在PC上进行编辑！"];
    }
    
    //[self didClickCellWithRO_NO:model.proxyID type:@"0"];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICMProxySearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICMProxySearchViewCell"];
    if (!cell) {
        cell = [[ICMProxySearchViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ICMProxySearchViewCell"];
    }
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    [cell updateDataWithModel:[self.dataSource objectAtIndex:indexPath.row]];
    return cell;
}

#pragma mark 时间控件确定回调方法
/*ICMDatePickerViewDelegate*/
- (void)calendarView:(PACACalendarView *)calendarView didSelectedDate:(NSDate*)selectedDate{
    if(calendarView == self.pickerFrom){
        self.selectedDateFrom = selectedDate;
        NSString *dateString = [selectedDate separatorStyleDateTimeString];
        self.labelFrom.contentTextFeild.text = dateString;
    }else{
        self.selectedDateTo = selectedDate;
        NSString *dateString = [selectedDate separatorStyleDateTimeString];
        self.labelTo.contentTextFeild.text = dateString;
    }
}

#pragma mark 时间控件清空回调方法
//清空时间
- (void)delTime:(PACACalendarView *)calendarView
{
    if(calendarView == self.pickerFrom){
        self.selectedDateFrom = nil;
        self.labelFrom.contentTextFeild.text = @"";
    }else{
        self.selectedDateTo = nil;
        self.labelTo.contentTextFeild.text = @"";
        
    }
}

- (PACACalendarView *)pickerFrom{
    if(!_pickerFrom){
        _pickerFrom = [PACACalendarView createCalendarViewWithDidSelectedDate:nil minDate:nil maxDate:nil andFrame:CGRectMake(ScreenWidth/2-150, ScreenHeight/2-150, ActualWidth(300), ActualWidth(380))];
        _pickerFrom.delegate = self;
        
    }
    return _pickerFrom;
}
- (PACACalendarView *)pickerTo{
    if(!_pickerTo){
        _pickerTo = [PACACalendarView createCalendarViewWithDidSelectedDate:nil minDate:nil maxDate:nil andFrame:CGRectMake(ScreenWidth/2-150, ScreenHeight/2-150, ActualWidth(300), ActualWidth(380))];
        _pickerTo.delegate = self;
        
    }
    return _pickerTo;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return CellHeight;
}

#pragma mark keyboard return key 回调
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.isSearchByDate = NO;
    [self.dataSource removeAllObjects];
    self.pageNo = 1;
    [self getTodayWithString:textField.text start:@"" end:@""];
    [textField resignFirstResponder];
    return YES;
}

#pragma mark 根据时间搜索列表数据
- (void)searchByDate{
    if(!self.labelFrom.contentText || [self.labelFrom.contentText isEqualToString:@""])
    {
        [self.view showString:@"开始时间未输入!" forSeconds:1.5f];
        return;
    }
    if(!self.labelTo.contentText || [self.labelTo.contentText isEqualToString:@""])
    {
        [self.view showString:@"结束时间未输入!" forSeconds:1.5f];
        return;
    }
    
    self.isSearchByDate = YES;
    [self.dataSource removeAllObjects];
    self.pageNo = 1;
    [self getTodayWithString:@"" start:self.labelFrom.contentText end:self.labelTo.contentText];
}

#pragma mark from时间控件调取
- (void)clickCalenderBtnFrom{
    [Window addSubview:self.pickerFrom];
}

#pragma mark to时间控件调取
- (void)clickCalenderBtnTo{
    [Window addSubview:self.pickerTo];
}

#pragma mark 预览
- (void)didClickPreViewWithIndex:(NSIndexPath *)index{
    ICMProxySearchModel *model = self.dataSource[index.row];
    //APP预生成 不可预览
    if(!model.proxyType || ![model.proxyType isEqualToString:ICMEnumIntToString(ICMEnumProxyTypeFromAPP)])
    {
        [self didClickCellWithRO_NO:model.proxyID type:@"1" andProxyStatus:model.proxyType];
    }
}

#pragma mark 调用搜索接口
- (void)getTodayWithString:(NSString *)text start:(NSString *)start end:(NSString *)end{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:text forKey:@"QUERY_CONDITION"];
    [parameters setObject:start forKey:@"QUERY_START_DATE"];
    [parameters setObject:end forKey:@"QUERY_END_DATE"];
    [parameters setObject:@(self.pageNo) forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:RepairOrderList parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if(self.pageNo == 1)
        {
            [self.dataSource removeAllObjects];
        }
        if ([data[@"CODE"] integerValue] == 200) {
            
            if (IsArr(data[@"TT_REPAIR_ORDER_LIST"])) {
                if(self.pageNo == 1)
                {
                    [self.dataSource removeAllObjects];
                }
                self.proxySearchList.mj_footer.hidden = NO;
                NSArray *dataArray = data[@"TT_REPAIR_ORDER_LIST"];
                for (NSDictionary *dic in dataArray) {
                    ICMProxySearchModel *model = [ICMProxySearchModel yy_modelWithDictionary:dic];
                    [self.dataSource addObject:model];
                }
                self.hasNext = YES;
                [self.proxySearchList.mj_footer endRefreshing];
            } else {
                if (self.dataSource.count == 0) {
                    self.proxySearchList.mj_footer.hidden = YES;
                    [self.view showString:@"暂无相关搜索结果！" forSeconds:1.5];
                } else {
                    self.hasNext = NO;
                    [self.proxySearchList.mj_footer endRefreshingWithNoMoreData];
                }
            }
            [self.proxySearchList reloadData];
        } else {
            [self.proxySearchList.mj_footer endRefreshing];
        }
    }];
}

#pragma mark 委托书跳转
//0跳委托书 1跳预览
- (void)didClickCellWithRO_NO:(NSString *)RO_NO type:(NSString *)type andProxyStatus:(NSString *)states{
    [self.activityModels removeAllObjects];
    [self.activityTempModels removeAllObjects];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:RO_NO forKey:@"RO_NO"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:RepairOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        
        ICMProxyBasicInfoModel *basicModel = [[ICMProxyBasicInfoModel alloc]init];
        if (IsArr(data[@"TT_REPAIR_ORDER"])) {
            basicModel = [ICMProxyBasicInfoModel yy_modelWithDictionary:data[@"TT_REPAIR_ORDER"][0]];
        }
        
        ICMStationModel *stationModel = [ICMStationModel mj_objectArrayWithKeyValuesArray:data[@"TT_RO_GLGW_LABOUR"]];
        
        ICMRepairMaintenancesModel *repairMaintenancesModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
        [repairMaintenancesModel createRepairMaintenanceRoModel];
        
        
        ICMRepairPartsArrayModel *repairPartsArrayModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
        [repairPartsArrayModel createRepairPartsRoModel];
        
        NSArray *dataArray = data[@"TT_ACTIVITY"];
        __block int countIndex = 0;
        if(dataArray && dataArray.count > 0)
        {
            if (dataArray.count != 0 && dataArray) {
                
                for (NSDictionary *activityData in dataArray) {
                    ICMProxyActivityViewModel *model = [[ICMProxyActivityViewModel alloc]init];
                    model.title = activityData[@"ACTIVITY_NAME"];
                    model.type = activityData[@"ACTIVITY_TYPE"];
                    model.subTitle = activityData[@"ACTIVITY_CODE"];
                    model.startTime = [ICrEAMTool getDateWithTimeInterval:activityData[@"SALES_DATE_BEGIN"]];
                    model.endTime = [ICrEAMTool getDateWithTimeInterval:activityData[@"SALES_DATE_END"]];
                    //ischecked 判断
                    if(activityData[@"IS_CHECKED"])
                    {
                        model.IS_CHECKED = activityData[@"IS_CHECKED"];
                    }
                    else
                    {
                        model.IS_CHECKED = ICMEnumIntToString(ICMEnumYESOrNONO);
                    }
                    [self.activityModels addObject:model];
                }
                for (ICMProxyActivityViewModel *viewModel in self.activityModels) {
                    
                    ICMProxyActivityViewModel *temp = [[ICMProxyActivityViewModel alloc]init];
                    temp.title = viewModel.title;
                    temp.type = viewModel.type;
                    temp.subTitle = viewModel.subTitle;
                    temp.startTime = viewModel.startTime;
                    temp.endTime = viewModel.endTime;
                    temp.IS_CHECKED = viewModel.IS_CHECKED;
                    [self.activityTempModels addObject:temp];
                    
                    if(viewModel.subTitle)
                    {
                        //去除首位空格和换行
                        viewModel.subTitle = [viewModel.subTitle stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                        NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/queryActivityDetail?ACTIVITY_CODE=%@",viewModel.subTitle];
                        [[[ICMRequestManager alloc] init]startGetRequestWithURL:url parameters:nil inHudView:self.view andResultBlock:^(id data, NSString *failText) {
                            countIndex++;
                            if (!failText) {
                                NSArray *labelArray = data[@"TT_ACTIVITY_LABOUR"];
                                NSArray *partsArray = data[@"TT_ACTIVITY_PART"];
                                for (NSDictionary *labourDic in labelArray) {
                                    ICMProxyActivityLabourModel *labelModel = [ICMProxyActivityLabourModel yy_modelWithJSON:labourDic];
                                    [viewModel.allActivityModel.TT_ACTIVITY_LABOUR addObject:labelModel];
                                    
                                    ICMRepairMaintenanceModel *labourTempModel = [ICMRepairMaintenanceModel yy_modelWithJSON:labourDic];
                                    labourTempModel.ACTIVITY_NO = labelModel.ACTIVITY_CODE;
                                    [temp.allActivityModel.TT_ACTIVITY_LABOUR addObject:labourTempModel];
                                }
                            for (NSDictionary *partDic in partsArray) {
                                    ICMProxyActivityPartsModel *partsModel = [ICMProxyActivityPartsModel yy_modelWithJSON:partDic];
                                    [viewModel.allActivityModel.TT_ACTIVITY_PART addObject:partsModel];
                                    
                                    ICMRepairPartsModel *partsTempModel = [ICMRepairPartsModel yy_modelWithJSON:partDic];
                                    partsTempModel.ACTIVITY_NO = partsModel.ACTIVITY_CODE;
                                    //给零件数量扶植
                                    partsTempModel.OBLIGATED_QUANTITY = partsModel.PART_QUANTITY;
                                    //单价
                                    partsTempModel.SALES_PRICE = partsTempModel.PART_SALES_PRICE;
                                    //零件销售价格
                                    float tempCount = [partsTempModel.OBLIGATED_QUANTITY floatValue];
                                    float tempPrice = [partsTempModel.SALES_PRICE floatValue];
                                    partsTempModel.PART_SALES_AMOUNT = [NSString stringWithFormat:@"%f",tempCount * tempPrice];
                                    [temp.allActivityModel.TT_ACTIVITY_PART addObject:partsTempModel];
                                }
                                
                            }else{
                                
                            }
                            if(countIndex == dataArray.count)
                            {
                                //跳转
                                if ([type integerValue] == 0) {
                                    //增加了除【常规保养、一般维修、服务活动、质量担保保养】之外的维修类型，在APP进行编辑时，则应弹出提示："请在PC端进行编辑！
                                    NSMutableArray *repairTypes = [[basicModel.RO_REPAIR_TYPE_NAME componentsSeparatedByString:@";"] mutableCopy];
                                    for(NSString *repairTypeStr in repairTypes)
                                    {
                                        if(![repairTypeStr isEqualToString:@"常规保养"] && ![repairTypeStr isEqualToString:@"一般维修"] && ![repairTypeStr isEqualToString:@"服务活动"] && ![repairTypeStr isEqualToString:@"质量担保保养"] && ![repairTypeStr isEqualToString:@""]&&![repairTypeStr isEqualToString:@"管理工位"]&&![repairTypeStr isEqualToString:@"快速保养"])
                                        {
                                            [self.view showString:@"请在PC端编辑该委托书！" forSeconds:1.5];
                                            return;
                                        }
                                    }
                                    
                                    ICMProxyHomePageViewController *HPVC = [[ICMProxyHomePageViewController alloc]init];
                                    if ([states isEqualToString:ICMEnumIntToString(ICMEnumProxyTypeNew)]) {
                                        HPVC.haveSyncmember=YES;
                                    }
                                    HPVC.repairMaintenancesModel = repairMaintenancesModel;
                                    HPVC.proxyBasicInfoModel =basicModel;
                                    HPVC.repairPartsArrayModel = repairPartsArrayModel;
                                    HPVC.activityModels = self.activityModels;
                                    HPVC.activityTempModels = self.activityTempModels;
                                    HPVC.stationModel = stationModel;
                                    
                                    
                                    [self.navigationController pushViewController:HPVC animated:YES];
                                }else{
                                    [self createLabourAndPartsExistDicWithLabour:repairMaintenancesModel WithPart:repairPartsArrayModel];
                                    ICMProxyPreviewViewController *PVC = [[ICMProxyPreviewViewController alloc]init];
                                    PVC.activityModels = [self previewActivitysWithDic:self.labourAndPartsExistDic];
                                    PVC.repairMaintenancesModel = repairMaintenancesModel;
                                    PVC.proxyBasicInfoModel = basicModel;
                                    PVC.repairPartsArrayModel = repairPartsArrayModel;
                                    PVC.stationsModel = stationModel;
                                    
                                    
                                    [self.navigationController pushViewController:PVC animated:YES];
                                }
                            }
                        }];
                    }
                    
                }
            }
        }
        else
        {
            //跳转
            if ([type integerValue] == 0) {
                //增加了除【常规保养、一般维修、服务活动、质量担保保养】之外的维修类型，在APP进行编辑时，则应弹出提示："请在PC端进行编辑！
                NSMutableArray *repairTypes = [[basicModel.RO_REPAIR_TYPE_NAME componentsSeparatedByString:@";"] mutableCopy];
                for(NSString *repairTypeStr in repairTypes)
                {
                    if(![repairTypeStr isEqualToString:@"常规保养"] && ![repairTypeStr isEqualToString:@"一般维修"] && ![repairTypeStr isEqualToString:@"服务活动"] && ![repairTypeStr isEqualToString:@"质量担保保养"] && ![repairTypeStr isEqualToString:@""]&&
                       ![repairTypeStr isEqualToString:@"管理工位"]&&
                       ![repairTypeStr isEqualToString:@"快速保养"]
                       )
                    {
                        [self.view showString:@"请在PC端编辑该委托书！" forSeconds:1.5];
                        return;
                    }
                }
                
                ICMProxyHomePageViewController *HPVC = [[ICMProxyHomePageViewController alloc]init];
                HPVC.repairMaintenancesModel = repairMaintenancesModel;
                HPVC.proxyBasicInfoModel =basicModel;
                HPVC.repairPartsArrayModel = repairPartsArrayModel;
                HPVC.activityModels = self.activityModels;
                HPVC.activityTempModels = self.activityTempModels;
                HPVC.stationModel = stationModel;
                [self.navigationController pushViewController:HPVC animated:YES];
            }else{
                [self createLabourAndPartsExistDicWithLabour:repairMaintenancesModel WithPart:repairPartsArrayModel];
                ICMProxyPreviewViewController *PVC = [[ICMProxyPreviewViewController alloc]init];
                PVC.activityModels = [self previewActivitysWithDic:self.labourAndPartsExistDic];
                PVC.repairMaintenancesModel = repairMaintenancesModel;
                PVC.proxyBasicInfoModel = basicModel;
                PVC.repairPartsArrayModel = repairPartsArrayModel;
                PVC.stationsModel = stationModel;
                [self.navigationController pushViewController:PVC animated:YES];
            }
        }
        
        
    }];
}

#pragma mark 根据活动里面项目和零件  和   项目和零件  生成对应关系数据字典 预览用
- (void)createLabourAndPartsExistDicWithLabour:(ICMRepairMaintenancesModel *)repairMaintenancesModel WithPart:(ICMRepairPartsArrayModel *)repairPartsArrayModel
{
    [self.labourAndPartsExistDic removeAllObjects];
    for(int i = 0;i<self.activityTempModels.count;i++)
    {
        ICMProxyActivityViewModel *actModel = self.activityTempModels[i];
        NSString *actCode = actModel.subTitle;
        NSMutableDictionary *actDic = [[NSMutableDictionary alloc] init];
        //该活动下项目的数组
        NSMutableArray *labourArray = actModel.allActivityModel.TT_ACTIVITY_LABOUR;
        //该活动下项目的字典
        NSMutableDictionary *labourDic = [[NSMutableDictionary alloc] init];
        for(int j = 0;j<labourArray.count;j++)
        {
            ICMRepairMaintenanceModel *labourModel = labourArray[j];
            NSString *labourCode = labourModel.LABOUR_CODE;
            [labourDic setObject:@(NO) forKey:labourCode];
        }
        //该活动下零件的数组
        NSMutableArray *partsArray = actModel.allActivityModel.TT_ACTIVITY_PART;
        //该活动下零件的字典
        NSMutableDictionary *partsDic = [[NSMutableDictionary alloc] init];
        for(int j = 0;j<partsArray.count;j++)
        {
            ICMRepairPartsModel *partModel = partsArray[j];
            NSString *partCode = partModel.PART_NO;
            [partsDic setObject:@(NO) forKey:partCode];
        }
        [actDic setObject:labourDic forKey:@"PANLabour"];
        [actDic setObject:partsDic forKey:@"PANParts"];
        [self.labourAndPartsExistDic setObject:actDic forKey:actCode];
        
        //项目数组
        NSMutableArray *proxyLabourArray = repairMaintenancesModel.TT_RO_LABOUR;
        for(int z = 0;z<proxyLabourArray.count;z++)
        {
            ICMRepairMaintenanceModel *model = proxyLabourArray[z];
            if([model.ACTIVITY_NO isEqualToString:actCode])
            {
                NSMutableDictionary *dic1 = [self.labourAndPartsExistDic objectForKey:actCode];
                NSMutableDictionary *dic2 = [dic1 objectForKey:@"PANLabour"];
                if([dic2 objectForKey:model.LABOUR_CODE])
                    [dic2 setObject:@(YES) forKey:model.LABOUR_CODE];
            }
        }
        
        //∫零件数组
        NSMutableArray *proxyPartsArray = repairPartsArrayModel.TT_RO_REPAIR_PART;
        for(int z = 0;z<proxyPartsArray.count;z++)
        {
            ICMRepairPartsModel *model = proxyPartsArray[z];
            if([model.ACTIVITY_NO isEqualToString:actCode])
            {
                NSMutableDictionary *dic1 = [self.labourAndPartsExistDic objectForKey:actCode];
                NSMutableDictionary *dic2 = [dic1 objectForKey:@"PANParts"];
                if([dic2 objectForKey:model.PART_NO])
                    [dic2 setObject:@(YES) forKey:model.PART_NO];
            }
        }
    }
}

#pragma mark 根据labourAndPartsExistDic 返回被选择的活动的被选择的项目和零件 预览用
- (NSMutableArray *)previewActivitysWithDic:(NSMutableDictionary *)dic
{
    NSMutableArray *temp = [[NSMutableArray alloc] init];
    NSMutableArray *previewActivityArray = [[NSMutableArray alloc] initWithArray:self.activityTempModels];
    for(int z=0;z< previewActivityArray.count;z++)
    {
        ICMProxyActivityViewModel *actModel = previewActivityArray[z];
        if([actModel.IS_CHECKED isEqualToString:ICMEnumIntToString(ICMEnumYESOrNOYES)])
        {
            NSString *actCode = actModel.subTitle;
            NSMutableDictionary *dic1 = [dic objectForKey:actCode];
            NSMutableDictionary *dic2 = [dic1 objectForKey:@"PANLabour"];
            NSMutableDictionary *dic3 = [dic1 objectForKey:@"PANParts"];
            
            //该活动下项目的数组
            NSMutableArray *tempLabourArray = [[NSMutableArray alloc] init];
            NSMutableArray *labourArray = [[NSMutableArray alloc] initWithArray:actModel.allActivityModel.TT_ACTIVITY_LABOUR];
            //该活动下项目的字典
            for(int i=0;i<labourArray.count;i++)
            {
                ICMRepairMaintenanceModel *labourModel = labourArray[i];
                NSString *labourCode = labourModel.LABOUR_CODE;
                if([dic2 objectForKey:labourCode])
                {
                    if(![[dic2 objectForKey:labourCode] boolValue])
                    {
                        [tempLabourArray addObject:labourModel];
                    }
                }
            }
            for(int ii = 0;ii<tempLabourArray.count;ii++)
            {
                [labourArray removeObject:tempLabourArray[ii]];
            }
            
            actModel.allActivityModel.TT_ACTIVITY_LABOUR = [[NSMutableArray alloc] initWithArray:labourArray];
            //该活动下零件的数组
            NSMutableArray *tempPartsArray = [[NSMutableArray alloc] init];
            NSMutableArray *partsArray = [[NSMutableArray alloc] initWithArray:actModel.allActivityModel.TT_ACTIVITY_PART];
            //该活动下零件的字典
            for(int j=0;j<partsArray.count;j++)
            {
                ICMRepairPartsModel *partModel = partsArray[j];
                NSString *partCode = partModel.PART_NO;
                if([dic3 objectForKey:partCode])
                {
                    if(![[dic3 objectForKey:partCode] boolValue])
                    {
                        [tempPartsArray addObject:partModel];
                        //[partsArray removeObject:partModel];
                    }
                }
            }
            for(int jj = 0;jj<tempPartsArray.count;jj++)
            {
                [partsArray removeObject:tempPartsArray[jj]];
            }
            actModel.allActivityModel.TT_ACTIVITY_PART = [[NSMutableArray alloc] initWithArray:partsArray];
        }
        else
        {
            [temp addObject:actModel];
            //[previewActivityArray removeObject:actModel];
        }
    }
    for(int zz = 0;zz<temp.count;zz++)
    {
        [previewActivityArray removeObject:temp[zz]];
    }
    
    return previewActivityArray;
}

- (NSMutableDictionary *)labourAndPartsExistDic
{
    if(!_labourAndPartsExistDic)
    {
        _labourAndPartsExistDic = [[NSMutableDictionary alloc] init];
    }
    return _labourAndPartsExistDic;
}

@end
